#include <iostream>

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};


ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
    
    ListNode *tmpA = headA;
    ListNode *tmpB = headB;

    while (tmpA != tmpB) {
		tmpA = tmpA ? tmpA->next : headB;
		tmpB = tmpB ? tmpB->next : headA;
    }

    return tmpA;
}

int main() {
    ListNode *headA = new ListNode(0);
    headA->next = new ListNode(9);
    headA->next->next = new ListNode(1);
    headA->next->next->next = new ListNode(2);
    headA->next->next->next->next = new ListNode(4);

    ListNode *headB = new ListNode(3);
    headB->next = headA->next->next->next;

    getIntersectionNode(headA, headB);

    return 0;
}